/**
 *
 * @Author 赵光
 * @Desc WebLogAppender
 * @Date 2020年5月23日
 */
package com.zlyx.easy.weblog.appender;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.zlyx.easy.asyn.utils.MsgUtils;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 *
 * @Author 赵光
 * @Desc WebLogAppender
 * @Date 2020年5月23日
 */
public class JedisLogAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

	protected JedisPool pool;

	protected String host;
	protected int port;
	protected String password;
	protected int database;
	protected int timeout;
	protected String channel;

	@Override
	protected void append(ILoggingEvent event) {
		Jedis client = pool.getResource();
		try {
			client.publish("easy-jedis-channel", MsgUtils.newMessage(channel, event.getFormattedMessage()));
		} catch (Exception e) {
			e.printStackTrace();
			client.close();
		} finally {
			if (client != null) {
				client.close();
			}
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getDatabase() {
		return database;
	}

	public void setDatabase(int database) {
		this.database = database;
	}

	/**
	 * @return the channel
	 */
	public String getChannel() {
		return channel;
	}

	/**
	 * @param channel the channel to set
	 */
	public void setChannel(String channel) {
		this.channel = channel;
	}

	@Override
	public void start() {
		try {
			super.start();
			GenericObjectPoolConfig config = new GenericObjectPoolConfig();
			config.setTestOnBorrow(true);
			pool = new JedisPool(config, host, port, timeout, password, database);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void stop() {
		try {
			super.stop();
			pool.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
